package org.dromara.comm_lhz.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.dromara.comm_lhz.entity.AsSpaceManageEntity;
import org.dromara.comm_lhz.entity.dto.AsSpaceDto;
import org.dromara.comm_lhz.entity.dto.AsSpaceManageDto;
import org.dromara.comm_lhz.mapper.AsSpaceManageHMapper;
import org.dromara.comm_lhz.service.AsSpaceImgHService;
import org.dromara.comm_lhz.service.AsSpaceManageHService;
import org.dromara.comm_lhz.util.QiniuUtil;
import org.dromara.comm_lhz.util.Result;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 空间管理控制器
 */
@RestController
@RequestMapping("/spaceManage")
@AllArgsConstructor
@Tag(name = "空间管理")
public class AsSpaceManageHController {

    private AsSpaceManageHService asSpaceManageHService;
    private AsSpaceManageHMapper asSpaceManageMapper;

    private AsSpaceImgHService asSpaceImgHService;

    QiniuUtil qiniuUtil;


    /**
     * 查询空间列表
     *
     * @param pageable 分页信息
     * @return 包含空间列表的Result对象
     */
    @GetMapping("/getSpaceManage")
    public Result getSpaceManage(Pageable pageable,String detailsName) {
        return Result.success("查询成功", asSpaceManageHService.getSpaceManage(pageable, detailsName));
    }



    /**
     * 查询空间详情
     *
     * @param asSpaceManageEntity 空间管理实体
     * @return 包含空间详情的Result对象
     */
    @GetMapping("/selSpaceManage")
    public Result selSpaceManage(AsSpaceManageEntity asSpaceManageEntity) {
        return Result.success("查询成功", asSpaceManageHService.selSpaceManage(asSpaceManageEntity));
    }

    /**
     * 新增空间详情
     *
     * @param asSpaceDto 空间数据传输对象
     */

    @PostMapping("/saveSpaceManage")
    public void saveSpaceManage(@RequestBody AsSpaceDto asSpaceDto) {
        asSpaceManageHService.insert(asSpaceDto);
    }

    /**
     * 根据id修改空间详情
     *
     * @param asSpaceDto
     * @return
     */
    @PostMapping("/updateSpaceManage")
    public void updateSpaceManage(@RequestBody AsSpaceDto asSpaceDto) {
       asSpaceManageHService.update(asSpaceDto);
    }

    /**
     * 根据id删除空间详情
     *
     * @param id 空间ID
     * @return 删除成功的Result对象或删除失败的Result对象
     */
    @GetMapping("/delSpaceManage")
    public Result delSpaceManage(Long id) {
        if (asSpaceManageHService.removeById(id)) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }

    }


    /**
     * 使用GET请求处理"/selectAll"路径，用于获取所有空间管理数据的列表
     * 该方法不接受任何请求参数，返回一个包含所有空间管理数据DTO的列表的响应实体
     *
     * @return 包含所有空间管理数据DTO的列表的响应实体
     */
    @GetMapping("/selectAll")
    @Operation(summary = "空间预约")
    public IPage<AsSpaceManageDto> selectAll(AsSpaceManageEntity asSpaceManageEntity, Pageable pageable) {
        // 设置分页参数，pageable.getPageNumber() 从 0 开始，所以加 1 来转换为从 1 开始计数
        Page<AsSpaceManageEntity> pageParam = new Page<>(pageable.getPageNumber() + 1, pageable.getPageSize());

        // 创建查询条件
        LambdaQueryWrapper<AsSpaceManageEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (asSpaceManageEntity.getDetailsName() != null) {
            queryWrapper.like(AsSpaceManageEntity::getDetailsName, asSpaceManageEntity.getDetailsName());
        }

        // 执行查询
        IPage<AsSpaceManageEntity> resultPage = asSpaceManageHService.page(pageParam, queryWrapper);

        // 将查询结果转换为DTO
        List<AsSpaceManageDto> dtoList = resultPage.getRecords().stream().map(entity -> {
            AsSpaceManageDto dto = new AsSpaceManageDto();
            dto.setId(entity.getId());
            dto.setName(entity.getName());
            dto.setDetailsName(entity.getDetailsName());
            dto.setReservationTimeStart(entity.getReservationTimeStart());
            dto.setReservationTimeEnd(entity.getReservationTimeEnd());
            dto.setPhone(entity.getPhone());
            dto.setRemarks(entity.getRemarks());
            return dto;
        }).collect(Collectors.toList());

        // 创建分页结果
        Page<AsSpaceManageDto> dtoPage = new Page<>(pageable.getPageNumber() + 1, pageable.getPageSize(), resultPage.getTotal());
        dtoPage.setRecords(dtoList);

        return dtoPage;
    }

    @Operation(summary = "新增空间预约")
    @PostMapping("/insertAsSpaceManage")
    @SaIgnore
    public ResponseEntity<Map<String, Object>> insertAsSpaceManage(
        @RequestParam(value = "file") MultipartFile file,
        @RequestParam(value = "detailsName") String detailsName,
        @RequestParam(value = "address") String address,
        @RequestParam(value = "availableTime") String availableTime,
        @RequestParam(value = "capacity") String capacity,
        @RequestParam(value = "extent") String extent) {

        Map<String, Object> response = new HashMap<>();
        try {
            if (file.isEmpty()) {
                response.put("message", "文件不能为空");
                return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
            }
            System.out.println("File received: " + file.getOriginalFilename());

            String imageUrl = qiniuUtil.uploadImage(file);

            AsSpaceManageEntity asPartyBuildingDTO = new AsSpaceManageEntity();
            asPartyBuildingDTO.setDetailsName(detailsName);
            asPartyBuildingDTO.setAddress(address);
            asPartyBuildingDTO.setAvailableTime(availableTime);
            asPartyBuildingDTO.setExtent(extent);
            asPartyBuildingDTO.setCapacity(capacity);
            asPartyBuildingDTO.setUrl(imageUrl);
            asPartyBuildingDTO.setThumbnail(imageUrl);
            asPartyBuildingDTO.setIsDelete(0L);
            asSpaceManageHService.save(asPartyBuildingDTO);

            response.put("message", "创建成功");
            response.put("imageUrl", imageUrl);
            return new ResponseEntity<>(response, HttpStatus.OK);

        } catch (Exception e) {
            response.put("message", "发生错误：" + e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @Operation(summary = "查询所有预约信息填报")
    @GetMapping("/selectAsSponsorAll")
    public AsSpaceManageEntity selectAsSponsorAll(AsSpaceManageEntity asSpaceManageEntity) {
            return asSpaceManageHService.selectAsSponsorAll(asSpaceManageEntity);
    }

    @Operation(summary = "查询我的预约")
    @GetMapping("/selectAsSpaceManageEntity")
    public List<Object> selectAsSpaceManageEntity(AsSpaceManageEntity asSpaceManageEntity) {
        return asSpaceManageHService.selectAsSpaceManageEntity(asSpaceManageEntity);
    }

}
